import Vue from 'vue'
import VueRouter from 'vue-router'

// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
};

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import(/* webpackChunkName: "Home" */ '../views/Home.vue'),
    meta: {
      showTab: true,
      activeNum: 0,
      isAlive:true
    },
    children: [
      {
        path: '/home/searchPopup',
        name: 'SearchPopup',
        component: () => import(/* webpackChunkName: "searchPopup" */ '../views/SearchPopup.vue'),
      }
    ]
  },
  {
    path: '/topic',
    name: 'Topic',
    component: () => import(/* webpackChunkName: "Topic" */ '../views/Topic.vue'),
    meta: {
      showTab: true,
      activeNum: 1,
      isAlive:true
    },
  },
  {
    path: '/category',
    name: 'Category',
    component: () => import(/* webpackChunkName: "Category" */ '../views/Category.vue'),
    meta: {
      showTab: true,
      activeNum: 2,
      isAlive:true
    },
    children: [
      {
        path: '/category/searchPopup',
        name: 'searchPopup',
        component: () => import(/* webpackChunkName: "searchPopup" */ '../views/SearchPopup.vue'),
      }
    ]
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import(/* webpackChunkName: "Cart" */ '../views/Cart.vue'),
    meta: {
      showTab: true,
      activeNum: 3
    },
  },
  {
    path: '/user',
    name: 'User',
    component: () => import(/* webpackChunkName: "User" */ '../views/User.vue'),
    meta: {
      showTab: true,
      activeNum: 4
    },
  },
  // 品牌制造商详情
  {
    path: '/branddetail/:id',  //动态路由
    name: 'branddetail',
    component: () => import(/* webpackChunkName: "branddetail" */ '../components/branddetail.vue'),
    meta: {
      showTab: false
    }
  },
  // 快捷导航列表
  {
    path: '/channel/:id',  //动态路由
    name: 'channel',
    component: () => import(/* webpackChunkName: "channel" */ '../components/channelList.vue'),
    meta: {
      showTab: false
    }
  },
  // 产品详情路由
  {
    path: '/pruductdetail/:id',  //动态路由
    name: 'Pruductdetail',
    component: () => import(/* webpackChunkName: "Pruductdetail" */ '../views/PruductDetail.vue'),
    meta: {
      showTab: false
    }
  },

]

const router = new VueRouter({
  mode:  'hash',
  routes
})

//路由导航守卫
router.beforeEach((to,from,next)=>{
  // console.log("to",to);  // 去往的路由对象
  // console.log("from",from); //来自的路由对象

  let token = localStorage.getItem('token')
  if (to.path == '/cart') {
    if(token){
      next()
    }else{
      Vue.prototype.$toast.fail('请先登录！')
      setTimeout(() => {
        next('/user')
      }, 1000);
    }
    return
  }
  next()   //必须调用这个next()才能跳转路由页面
})

export default router
